from fastapi import APIRouter, BackgroundTasks, Depends, Request
from fastapi.responses import JSONResponse
import uuid
import logging

from src.core.pipeline import PipelineManager
from src.web.v1.services import PipelineManagerDep

router = APIRouter()

from src.web.v1.routes import (
    ask,
    ask_details,
    chart,
    chart_adjustment,
    question_recommendation,
    relationship_recommendation,
    semantics_description,
    semantics_preparation,
    sql_answer,
    sql_expansion,
    sql_pairs,
    sql_question,
)

router.include_router(ask.router, prefix="/ask", tags=["ask"])
router.include_router(ask_details.router, prefix="/ask-details", tags=["ask-details"])
router.include_router(chart.router, prefix="/chart", tags=["chart"])
router.include_router(
    chart_adjustment.router, prefix="/chart-adjustment", tags=["chart-adjustment"]
)
router.include_router(
    question_recommendation.router,
    prefix="/question-recommendation",
    tags=["question-recommendation"],
)
router.include_router(
    relationship_recommendation.router,
    prefix="/relationship-recommendation",
    tags=["relationship-recommendation"],
)
router.include_router(
    semantics_description.router,
    prefix="/semantics-description",
    tags=["semantics-description"],
)
router.include_router(
    semantics_preparation.router,
    prefix="/semantics-preparation",
    tags=["semantics-preparation"],
)
router.include_router(sql_answer.router, prefix="/sql-answer", tags=["sql-answer"])
router.include_router(
    sql_expansion.router, prefix="/sql-expansion", tags=["sql-expansion"]
)
router.include_router(sql_pairs.router, prefix="/sql-pairs", tags=["sql-pairs"])
router.include_router(
    sql_question.router, prefix="/sql-question", tags=["sql-question"]
)

logger = logging.getLogger("wren-ai-service")

@router.get("/health")
async def health_check():
    return {"status": "ok"}


@router.middleware("http")
async def add_process_time_header(request: Request, call_next):
    # 为每个请求生成一个唯一的 ID
    request.state.request_id = str(uuid.uuid4())
    response = await call_next(request)
    return response


def get_pipeline_manager_with_request_id(
    request: Request, background_tasks: BackgroundTasks, pipeline_manager: PipelineManagerDep
) -> PipelineManager:
    """Get a pipeline manager with a request ID."""
    pipeline_manager.set_background_tasks(background_tasks)
    pipeline_manager.set_id(request.state.request_id)
    return pipeline_manager


@router.post("/graphql")
async def graphql_endpoint(request: Request):
    # 添加日志记录
    logger.info("GraphQL request received")
    
    # 获取请求体
    body = await request.json()
    logger.info(f"GraphQL request body: {body}")
    
    # 处理请求
    # ... existing code ...
    
    # 记录响应
    logger.info(f"GraphQL response: {response}")
    return response 